package generator.util

import generator.common.Conversion

import java.io.FileReader
import scala.io.Source
import scala.util.matching.Regex

class FixedConversion extends Conversion {
  var reader:FileReader = null
  var regex:Regex = null
  var content:String = null
  var fileName:String = null
  var fxtlName:String = null

  override def convert(): Unit = {
    load(fxtlName)

    content = new FileReader(fileName).toString
  }

  def convert(fileName:String,transform:Regex.Match=>String): String = {
    if (fxtlName != null) this.fxtlName = fxtlName
    this.fileName = fileName
    convert()
    regex.replaceAllIn(content,transform)
  }

  def get(fileName: String,fxtlName:String=null): List[String] = {
    if (fxtlName != null) this.fxtlName = fxtlName
    this.fileName = fileName
    convert()
    regex.findFirstMatchIn(content).get.subgroups
  }

  def getAll(fileName: String, fxtlName: String = null): List[List[String]] = {
    if (fxtlName != null) this.fxtlName = fxtlName
    this.fileName = fileName
    convert()
    regex.findAllMatchIn(content).map(_.subgroups).toList
  }

  def load(fileName:String): Unit = {
    if (!fileName.equals(fxtlName)) {
      this.fxtlName = fileName
      content = Source.fromFile(fileName).mkString
      content = content.replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)").replaceAll("\\{", "\\\\{").replaceAll("\\}", "\\\\}").replaceAll("[ ]+", "\\s*")
      content = "@[^#]+#".r.replaceAllIn(content, "([^\n]*)")
      regex = content.r
    }
  }
}

object FixedConversion {
  def apply():FixedConversion = {
    new FixedConversion()
  }
}
